package Impl;

import Util.JDBC;
import dao.TopicDao;
import entity.TopicInfo;
import entity.page.DetailPage;
import entity.page.IndexPage;
import entity.page.ListPage;
import jdk.nashorn.internal.objects.annotations.Where;

import javax.management.Query;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class TopicDaoImpl implements TopicDao {
    adminDaoImpl adminDao = new adminDaoImpl();
    public ResultSet query(PreparedStatement ps, Object[] param , Integer start, Integer maxCount){
        ResultSet rs = null;
        try {
            if(param != null){
                for(int i=0; i<param.length; i++){
                    ps.setObject(i+1, param[i]);
                }
            }
            // 设置查询到的记录的最大索引
            if(start != null && maxCount != null)
                ps.setMaxRows(start+maxCount);
            rs = ps.executeQuery();
            // 设置查询到的记录的起始索引
            if(start != null && maxCount != null){
                rs.first();
                rs.relative(start-1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    @Override
    public IndexPage getALLTopicLastTimeById(Integer sId) {
        IndexPage indexPage = new IndexPage();
        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select (select uname from user where user.uId= tb.tUid ) as author,tTopic as title,tPublishTime as publishTime,tid"
                + " from"
                + " (select * from topicInfo where tPublishTime =(select max(tPublishTime) from topicInfo where tSid = ?)) as tb";

        try
        {
            ps = con.prepareStatement(sql);
            Object[] param = {sId};
            rs = query(ps, param,null,null);
            if(rs!=null&&rs.next())
            {
//                System.out.println("tid:"+rs.getInt("tId"));
                indexPage.setTid(rs.getInt("tId"));
                indexPage.setAuthor(rs.getString("author"));
                indexPage.setTtopic(rs.getString("title"));
                indexPage.setTpublishtime(rs.getDate("publishTime"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBC.closeAll(con,ps,rs);
        }
//        System.out.println(indexPage.toString());
        return indexPage;
    }

    @Override
    public DetailPage getTopicInfoAndUserInfoById(Integer tid) {
        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        DetailPage detail = new DetailPage();
        String sql = "select tTopic,tContents,tPublishTime,tModifyTime,tId,tUid,"
                + "(select uname from  user where user.uId = topicInfo.tuid) as tName,"
                + "(select uFace from  user where user.uId = topicInfo.tuid) as tFace,"
                + "(select uRegTime from  user where user.uId = topicInfo.tuid) as tRegTime,"
                + "(select uType from  user where user.uId = topicInfo.tuid) as tUserType,"
                + "(select uSex from  user where user.uId = topicInfo.tuid) as tSex"
                + " from topicInfo where tid = ?";

        try
        {
            ps = con.prepareStatement(sql);
            Object[] param = {tid};
            rs = query(ps, param,null,null);
            if(rs!=null&&rs.next())
            {
                detail.setContents(rs.getString("tContents"));
                detail.setFace(rs.getString("tFace"));
                detail.setModifytime(rs.getTimestamp("tModifyTime"));
                detail.setAuthor(rs.getString("tName"));
                detail.setPublishtime(rs.getTimestamp("tPublishTime"));
                detail.setRegtime(rs.getDate("tRegTime"));
                detail.setTitle(rs.getString("tTopic"));
                detail.setType(rs.getInt("tUserType"));
                detail.setSex(rs.getBoolean("tSex"));
                detail.setId(rs.getInt("tId"));
                detail.setUid(rs.getInt("tUid"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBC.closeAll(con,ps,rs);
        }

        return detail;
    }

    @Override
    public ArrayList<ListPage> getTopicInfobyid(Integer sid) {
        ArrayList<ListPage> listPages = new ArrayList<>();
        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select tId,tTopic,tReplyCount,(select uname from user where uid = topicInfo.tuid) as tuid "
                + "from topicInfo where tsid = ? order by tPublishTime desc";
        try
        {
            ps = con.prepareStatement(sql);
            Object[] param = {sid};
            rs = query(ps, param , null, null);
            while(rs.next())
            {
                ListPage listPage = new ListPage();
                listPage.setAuthor(rs.getString("tuid"));
                listPage.setReplycount(rs.getInt("tReplyCount"));
                listPage.setTid(rs.getInt("tId"));
                listPage.setTitle(rs.getString("tTopic"));
                listPages.add(listPage);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBC.closeAll(con,ps,rs);
        }
        return listPages;
    }

    @Override
    public ArrayList<TopicInfo> getTopicInfo(int sid) {
        ArrayList<TopicInfo> listPages = new ArrayList<>();
        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from topicinfo where tsid = ?";
        try
        {
            ps = con.prepareStatement(sql);
            Object[] param = {sid};
            rs = query(ps, param , null, null);
            while(rs.next())
            {
                TopicInfo topicInfo = new TopicInfo();
                topicInfo.setTid(rs.getInt("tId"));
                topicInfo.setTtopic(rs.getString("tTopic"));
                topicInfo.setTcontents(rs.getString("tContents"));
                topicInfo.setTreplycount(rs.getInt("tReplyCount"));
                topicInfo.setTuid(rs.getInt("tUid"));
                topicInfo.setTpublishtime(rs.getString("tPublishTime"));
                topicInfo.setTmodifytime(rs.getString("tModifyTime"));
                topicInfo.setTuid(rs.getInt("tuid"));
                listPages.add(topicInfo);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBC.closeAll(con,ps,rs);
        }
        return listPages;
    }
    @Override
    public void insertTopicInfo(String send_title, String send_content, Integer child_sid, Integer uid) {
        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "insert into topicinfo(tSid,tuid,tTopic,tContents,tPublishTime)"
                + " values(?,?,?,?,?)";

        send_content = send_content.replace("<", "&lt;");
        send_content = send_content.replace(">", "&gt;");
        send_content = send_content.replace(" ", "&nbsp");
        send_content = send_content.replace("\r\n", "<br>");

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        Object[] param = {child_sid, uid, send_title, send_content, dateString};
        System.out.println("TopicDaoImpl.java: tuid: " + uid);
        adminDao.commonUp(sql, param);
    }

    @Override
    public void getTopicCountById(Integer child_sid) {
        String sql = "update plate set sTopicCount = "
                + " (select count(*) as topicCount from topicinfo where tsid = ?)"
                + " where sid = ?";

        Object[] param = {child_sid, child_sid};
        adminDao.commonUp(sql, param);
        System.out.println("TopicDaoImpl.java: " + child_sid);
    }

    @Override
    public void modifyTopicInfo(String title, String content, Integer sid, Integer uid, Integer tid) {

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);

        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String sql1 = "update topicinfo set tSId=? where tid=?";
        String sql2 = "update topicinfo set tTopic=? where tid=?";
        String sql3 = "update topicinfo set tContents=? where tid=?";
        String sql4 = "update topicinfo set tModifyTime=? where tid=?";


        try
        {
            ps = con.prepareStatement(sql1);
            ps.setInt(1,sid);
            ps.setInt(2,tid);
            ps.executeUpdate();

            ps = con.prepareStatement(sql2);
            ps.setString(1,title);
            ps.setInt(2,tid);
            ps.executeUpdate();

            ps = con.prepareStatement(sql3);
            ps.setString(1, content);
            ps.setInt(2,tid);
            ps.executeUpdate();


            ps = con.prepareStatement(sql4);
            ps.setString(1,dateString);
            ps.setInt(2,tid);
            ps.executeUpdate();

        }
        catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBC.closeAll(con,ps,rs);
        }

    }




    @Override
    public void deleteTopicById(Integer tId) {
        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        String sql="delete from topicinfo where tId=?";
        ResultSet rs = null;
        try
        {
            ps = con.prepareStatement(sql);
            ps.setInt(1,tId);
            ps.executeUpdate();
        }
        catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBC.closeAll(con,ps,rs);
        }
    }

    @Override
    public void getRepltCountByid(int tid) {
            String sql = "update topicinfo set tReplyCount = "
                    + " (select count(*) as replyCount from reply where rtid = ?)"
                    + " where tid = ?";

            Object[] param = {tid, tid};
            adminDao.commonUp(sql, param);
            System.out.println("TopicDaoImpl.java: " + tid);
    }

    @Override
    public boolean deleteReplyById(Integer tId)
    {
        Connection con = JDBC.getConnection();
        PreparedStatement ps = null;
        String sql="delete from replyinfo where rTId=?";
        ResultSet rs = null;

        boolean valid=true;
        try
        {
            ps = con.prepareStatement(sql);
            ps.setInt(1,tId);
            ps.executeUpdate();

        }
        catch (SQLException e) {
            e.printStackTrace();
            valid=false;
        } finally {
            JDBC.closeAll(con,ps,rs);
        }
        return valid;
    }


}
